# encoding=utf8
import re
import time

import requests
from flask import request
from flask_restful import Resource

from common.db import User, KeywordData

limit = 2
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) '
                         'Chrome/17.0.963.56 Safari/535.11',
           'Referrer': 's.taobao.com'
           }


class Taobao(Resource):
    @staticmethod
    def post():
        keyword = request.json.get("keyword")
        if keyword is None:
            return {"status": False, "msg": "添加失败"}
        url = 'https://s.taobao.com/search'
        rateUrl = 'https://rate.taobao.com/feedRateList.htm'
        payload = {'q': keyword, 's': '1', 'ie': 'utf8'}  # 字典传递url参数，第二字段写要搜索的关键词
        rateload = {'auctionNumId': '44404493527', 'userNumId': '839556000', 'currentPageNum': '1', 'pageSize': '20',
                    'rateType': '1', 'folded': '0', 'ie': 'utf8'}  # 字典传递url参数
        print("爬数据开始，搜索关键词为：" + keyword)
        for k in range(0, limit):
            payload['s'] = 44 * k + 1  # 此处改变的url参数为s，s为1时第一页，s为45是第二页，89时第三页以此类推
            resp = requests.get(url, params=payload, headers=headers)
            print(resp.url)
            resp.encoding = 'utf-8'  # 设置编码
            title = re.findall(r'"raw_title":"([^"]+)"', resp.text, re.I)  # 正则保存所有raw_title的内容，这个是书名，下面是价格，地址
            price = re.findall(r'"view_price":"([^"]+)"', resp.text, re.I)
            loc = re.findall(r'"item_loc":"([^"]+)"', resp.text, re.I)
            sales = re.findall(r'"view_sales":"([^"]+)"', resp.text, re.I)
            pid = re.findall(r'"nid":"([^"]+)"', resp.text, re.I)
            x = len(title)  # 每一页商品的数量
            for i in range(0, x):  # 把列表的数据保存到文件中
                rateload['auctionNumId'] = pid[i]
                rateload['rateType'] = 1
                respRate = requests.get(rateUrl, params=rateload, headers=headers)
                respRate.encoding = 'utf-8'  # 设置编码
                ratevalue = re.findall(r'"total":([^,]+)', respRate.text, re.I)
                positive = ratevalue[0]
                rateload['rateType'] = 0
                respRate = requests.get(rateUrl, params=rateload, headers=headers)
                respRate.encoding = 'utf-8'  # 设置编码
                ratevalue = re.findall(r'"total":([^,]+)', respRate.text, re.I)
                middle = ratevalue[0]
                rateload['rateType'] = -1
                respRate = requests.get(rateUrl, params=rateload, headers=headers)
                respRate.encoding = 'utf-8'  # 设置编码
                ratevalue = re.findall(r'"total":([^,]+)', respRate.text, re.I)
                negative = ratevalue[0]
                current = i + (k * 44)
                allcount = limit * 44
                print(" 第 " + str(current) + " 条商品数据 -- 总进度：" + str('%.2f' % ((current / allcount) * 100)) + "%")
        return {"status": True, "msg": "添加成功"}


class Register(Resource):
    @staticmethod
    def post():
        username = request.json.get('username')
        password = request.json.get('password')
        nickname = request.json.get('nickname')
        if username is None or password is None:
            return {'status': False, "msg": "用户名或密码不能为空"}
        from run import session
        if session.query(User).filter_by(username=username).first() is not None:
            return {'status': False, "msg": "用户名已存在"}
        user = User(username=username)
        user.hash_password(password)
        user.nickname = nickname
        user.register_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        session.add(user)
        try:
            session.commit()
        except:
            session.rollback()
        return {'status': True, 'msg': "注册成功"}


class KeywordList(Resource):
    @staticmethod
    def get():
        from run import session
        keywords = session.query(KeywordData).all()
        data = []
        for keyword in keywords:
            data.append(keyword.to_json())
        return {"status": True, "data": data, "msg": "获取成功"}
